package com.lightsh.screens;

import java.util.Random;

import org.jbox2d.collision.shapes.Shape;
import org.jbox2d.common.Vec2;
import org.jbox2d.dynamics.Body;
import org.jbox2d.dynamics.ContactFilter;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.hardware.SensorEvent;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Toast;

import com.lightsh.body.PhysicsBody;
import com.lightsh.body.RectangleImpl;
import com.lightsh.gui.PhysicsScreen;
import com.lightsh.jbox2d.R;
import com.lightsh.object.BaseObject;
import com.lightsh.object.CircleObject;
import com.lightsh.object.PolygonObject;
import com.lightsh.object.RectangleObject;
import com.lightsh.object.SimpleObject;
import com.lightsh.object.SurfaceObject;
import com.lightsh.things.Plane;
import com.lightsh.things.SkyBarrier;
import com.lightsh.things.SurfaceBtn;
import com.lightsh.things.SurfaceBtnPolygon;
import com.lightsh.things.SurfaceBtnRectangle;
import com.lightsh.utility.Debugger;

public class PlaneScreen extends PhysicsScreen{
	private static final String TAG = "PlaneScreen";
	private static final boolean DEBUG = true;
	
	private Plane mPlane;
	
	private boolean mSensorControl = true;
	private long mLastControlKeyDown;
	private int mSeriesControl;
	
	private boolean mContactable = true;
	
	private boolean mNeedResetWord;
	
	private int mGenerateBarrierDistance;
	/**
	 * 记录最近生成的障碍物的y位置
	 */
	private int mLastBarrierPosition;
	
	public PlaneScreen(Context context, int screenW, int screenH) {
		super(context, screenW, screenH, screenW, screenH * 100);
		enableSensor(true);
		// 创建世界了
		createWorld(1/10f, true);
		initPlaneInfo();
		
		mRand.setSeed(System.currentTimeMillis());
		
	}
	private void initPlaneInfo(){
		mGenerateBarrierDistance = mScreenH * 2;		
		mLastBarrierPosition = mScreenH;
		
		mLastControlKeyDown = 0;
		mSeriesControl = 0;
		
		enableContact(true);	
		
		mbEnd = false;
		resume();
		mNeedResetWord = false;
		
		mPlane = new Plane(this, mScreenW / 2, 100, 1, 0, 0, 60, 80);
		mPlane.create();
		
		// FIXME 测试目的，增加一个surface按钮
		SimpleObject baseObject = new SurfaceBtn(this, 100, mScreenH - 100, 100);
		baseObject.create();
		addTouchListener(baseObject);
		
//		final Vec2[] fStarVecs = new Vec2[]{
//			new Vec2(0, -4),
//			//new Vec2(1, -2),
//			new Vec2(4, -2),
//			//new Vec2(2, 0),
//			new Vec2(3, 3),
//			//new Vec2(0, 1),
//			new Vec2(-3, 3),
//			//new Vec2(-2, 0),
//			new Vec2(-4, -2),
//			//new Vec2(-1, -2)
//		};
//		float scale = 10f;
//		PolygonObject polygonObject = new SurfaceBtnPolygon(this, 300, mScreenH - 100);
//		for(Vec2 vec : fStarVecs){
//			polygonObject.add(vec.mul(scale));
//		}
//		polygonObject.create();
//		
//		polygonObject = new SurfaceBtnRectangle(this, mScreenW - 100, mScreenH - 100, 100, 100);
//		polygonObject.create();
		
		float friction = 1f;
		RectangleImpl left = new RectangleImpl(this, 0, getWorldHeight() >> 1, 3, getWorldHeight() >> 1, 0, friction, 0.1f);		
		RectangleImpl right = new RectangleImpl(this, getWorldWidth(), getWorldHeight() >> 1, 3, getWorldHeight() >> 1, 0, friction, 0.1f);
		RectangleImpl top = new RectangleImpl(this, getWorldWidth() >> 1, 0, getWorldWidth() >> 1, 3, 0, friction, 0.1f);
		RectangleImpl bottmp = new RectangleImpl(this, getWorldWidth() >> 1, getWorldHeight(), getWorldWidth() >> 1, 3, 0, friction, 0.1f);
		left.setColor(Color.BLACK);
		right.setColor(Color.BLACK);
		top.setColor(Color.BLACK);
		bottmp.setColor(Color.BLACK);
		
		left.create();
		right.create();
		top.create();
		bottmp.create();		
	}
	
	/**
	 * 重新初始化world中的物体
	 */
	private void resetWorld(){
		clearAllList();
		initPlaneInfo();
	}
	
	public void restartGame(){
		if(mbEnd){
			mNeedResetWord = true;
		}
	}
	
	private void trackPlane(){
		Vec2 planePositon = mPlane.getPosition();
		moveScreenTo(getCurrentRectClone().left, (int)(meterToPx(planePositon.y) - mScreenH / 2 / getScreenScale()));
		
	}
	@Override
	public void onUpdate(){
		if(mbEnd && mNeedResetWord){
			resetWorld();
			return;
		}		
		// 这里需要先完成跟踪飞机，然后才能update里面的其他物体
		if(!isPause() && !mPlane.isEnd()){
			trackPlane();
			checkGenerate();
		}
		super.onUpdate();
		
		if(mPlane.isEnd() && !mbEnd){
			// FIXME 结束
			mbEnd = true;
			Log.e(TAG, "end");
		}
	}
	
	
	@Override
	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		onEndDraw(canvas);
	}
	protected void onEndDraw(Canvas canvas) {
		if(mPlane.isEnd()){
			
			float textSize = mPaint.getTextSize();
			mPaint.setTextSize(40);
			canvas.drawText(mContext.getString(R.string.gameIsEnd), mScreenW / 2 - 50, mScreenH / 2, mPaint);
			
			mPaint.setTextSize(textSize);
			// FIXME 当飞机失事后，主要做的东西就是显示失败信息，并出现重试按钮等
			// 考虑这两部分的UI显示，是由draw方法绘制，还是使用android的UI控件显示
			// 注意，如果使用UI控件，这里是子线程，理论上是不能弹出dialog等东西的
		}
	}
	@Override
	public void onSensorChange(SensorEvent event) {
		super.onSensorChange(event);
		if(isSensorEnable() && mSensorControl){
			mPlane.updateVelocity(mXGravity);
		}
	}
	
	
	
	private void checkGenerate(){
		Rect rect = getCurrentRectClone();
		// 一次生成一个物体
		if(mLastBarrierPosition - rect.top <= mGenerateBarrierDistance){
			generateBarrierForScreen(mLastBarrierPosition);
		}
	}
	
	private final static int MIN_BARRIER_DISTANCE = 100;
	private final static int MAX_BARRIER_DISTANCE = 200;
	private void generateBarrierForScreen(int startPosition){
		
		int halfWidth = mScreenW / 4;
		int halfHeight = 30;
		
		halfWidth += mRand.nextInt(halfWidth / 4) * (mRand.nextBoolean() ? -1 : 1);
		halfHeight += mRand.nextInt(halfHeight / 2) * (mRand.nextBoolean() ? -1 : 1);
		
		
		int yPosition = mRand.nextInt(MAX_BARRIER_DISTANCE - MIN_BARRIER_DISTANCE) + MIN_BARRIER_DISTANCE;
		// 由于这个位置是物体的中心点，所以要做halfHeight偏移
		yPosition += mLastBarrierPosition + halfHeight;
		
		boolean left = mRand.nextBoolean();
		generateBarrier(yPosition, left, halfHeight, halfWidth);
		
		
	}
	
	private boolean generateBarrier(int yPosition, boolean left, int halfHeight, int halfWidth){
		SkyBarrier barrier = new SkyBarrier(this, left ? halfWidth : mScreenW - halfWidth, yPosition, halfWidth, halfHeight, 0, 0, 0);
		barrier.setColor(Color.YELLOW);
		barrier.create();
		mLastBarrierPosition = yPosition + halfHeight;		
		return true;
	}
	@Override
	public boolean onTouchEvent(MotionEvent ev) {
		if(!handleTouchEvent(ev)){
			return super.onTouchEvent(ev);
		}
		return true;
	}
	
	
	private boolean handleTouchEvent(MotionEvent ev){
		if(!isPause() && !mSensorControl){
			// 是否在左右按钮的范围内
			float targetX = ev.getX();
			float targetY = ev.getY();
			
			if(targetY > mScreenH / 4 * 3){
				boolean changeDirection = false;
				boolean left = false;
				if(targetX < mScreenW / 4){
					left = true;
				}
				if(left || targetX > mScreenW / 4 * 3){
					if((ev.getAction() & MotionEvent.ACTION_MASK) == MotionEvent.ACTION_DOWN){
						mLastControlKeyDown = System.nanoTime();
						mSeriesControl = 0;
						changeDirection = true;
					}else{
						long current = System.nanoTime();
						long timeInterval = 0;
						switch(mSeriesControl){
						case 0:
							timeInterval = 100;
							break;
						case 1:
							timeInterval = 80;
							break;
						case 2:
							timeInterval = 80;
							break;
						case 3:
							timeInterval = 80;
							break;
						}
						timeInterval *= 1000 * 1000;
						
						if(current - mLastControlKeyDown > timeInterval){
							if(timeInterval > 0){
								mSeriesControl++;
							}
							mLastControlKeyDown = current;
							changeDirection = true;
						}
					}
				}
				if(changeDirection){
					mPlane.onDirectionClick(left);
				}
				
				return true;
			}
		}
		return false;
	}
	
	public boolean isSensorControl(){
		return mSensorControl;
	}
	public void enableSensorControl(boolean enable){
		mSensorControl = enable;
	}
	
	public boolean isContactable(){
		return mContactable;
	}
	public void enableContact(boolean bContactable){
		if(mContactable != bContactable){
			mContactable = bContactable;
			if(mContactable){
				getWorld().setContactFilter(ContactFilter.DEFAULT_FILTER);
			}else{
				getWorld().setContactFilter(new ContactFilter() {
					
					@Override
					public boolean shouldCollide(Shape shape1, Shape shape2) {
						return false;
					}
					
					@Override
					public boolean rayCollide(Object userData, Shape shape) {
						return false;
					}
				});
			}
		}
	}
	@Override
	public void pause() {
		super.pause();
		enableTouchTransfer(true);
	}
	@Override
	public void resume() {
		super.resume();
		enableTouchTransfer(false);
	}
	
	
}
